from app.schema.base import RespBaseSchema
from app.service.base import BaseService
from app.dao.ai import AiDao
from app.core.local_file import LocalFile
from app.config.es import EsConfig
from app.retriever.es import MyElasticsearch
from app.retriever.milvus import MilvusVectorStore
from ..dao.file import FileDao
from ..model.file import File
from app.schema.file import *
from app.chain.prompt_call_chain import generate_system_prompt
import asyncio


class FileService(BaseService):
    def __init__(self, auth_data: dict = {}):
        user_id = auth_data.id
        self.Model = File
        self.dao = FileDao(user_id)
        self.dao.Model = File

        super().__init__(user_id, auth_data)

    def update_file(self, file: UpdataFileSchema):
        res = self.dao.update(file)
        return res

    def create_file(self, file: UploadFileSchema, auth_data: dict):
        res = self.create(file)
        file_milvus = MilvusFileSchema(
            file_id=res.id, file_name=file.name, url=file.url
        )
        return RespDataSchema(data=file_milvus)

    async def load_milvus(self, file_milvus: MilvusFileSchema, auth_data: dict):
        try:
            ai_info = AiDao().read_by_user_id(auth_data.id)
            milvus = MilvusVectorStore(ai_info.vector_name)
            # es_store=MyElasticsearch(ai_info.vector_name)
            local_file = LocalFile(file_milvus, milvus=milvus)
            await local_file.download_file()  # 下载文件到本地
            await local_file.split_file_to_docs()  # 切割文件,上传并删除本地文件
            res = self.update(UpdataFileSchema(id=file_milvus.file_id, status=1))

            # await self.get_all_file(auth_data)
            return res
        except Exception as e:
            file_info = self.dao.read(file_milvus.file_id)
            file_info.status = 2
            self.dao.update(file_info)
            return RespBaseSchema(code=400, message=str(e))

    async def delete_file(self, id: int, auth_data: dict):
        file_info = self.dao.read(id)
        aidao = AiDao()
        ai_info = aidao.read(file_info.ai_id)
        res = self.delete(id)
        try:
            milvus = MilvusVectorStore(ai_info.vector_name)
            # es_store = MyElasticsearch(ai_info.vector_name)
            await milvus.adelete_by_expr(expr=f"file_id == {id}")

            # 搜索请求体
            # search_body = {
            #     "query": {
            #         "term": {
            #         "metadata.file_id": id
            #         }
            #     }
            # }
            # 获取es中file_id为id的文档
            # ids = await es_store.get_ids(search_body)
            # await es_store.adelete(ids)
        except:
            pass

        # await self.get_all_file(auth_data)
        return res

    async def get_all_file(self, auth_data: dict):
        aidao = AiDao()
        file_list = FileDao().read_by_user_id(auth_data.id)
        ai_info = aidao.read_by_user_id(auth_data.id)
        content_arr = []
        for file_info in file_list:
            milvus = MilvusVectorStore(ai_info.vector_name)
            # es_store=MyElasticsearch(ai_info.vector_name)
            local_file = LocalFile(
                MilvusFileSchema(
                    file_id=file_info.id, file_name=file_info.name, url=file_info.url
                ),
                milvus=milvus,
            )
            await local_file.download_file()
            content = await local_file.split_file_to_docs(is_insert=False)
            content_arr.append(
                FileContextWithName(content=content, file_name=file_info.name)
            )
        # 获取系统提示词
        system_prompt = await generate_system_prompt(
            ai_name=ai_info.name, content_list=content_arr
        )
        # 更新系统提示词
        ai_info.remark = system_prompt
        res = aidao.update(ai_info)

        return res
